//
//  SEHospitalizeOrderDetailViewController.swift
//  SmartEyeForPatient
//
//  Created by qdsg on 2021/4/16.
//

import UIKit

class SEHospitalizeOrderDetailViewController: SEBaseViewController {

    @IBOutlet weak var tableView: UITableView! {
        didSet {
            tableView.isHidden = true
            tableView.tableFooterView = UIView()
            tableView.separatorColor = UIColor.init(hex: "EBECF0")
            tableView.separatorInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
            tableView.register(UINib(nibName: SEHospitalizeOrderDoctorCell.className, bundle: nil), forCellReuseIdentifier: SEHospitalizeOrderDoctorCell.reuseId)
            tableView.register(UINib(nibName: SEHospitalizeOrderPatientCell.className, bundle: nil), forCellReuseIdentifier: SEHospitalizeOrderPatientCell.reuseId)
            tableView.register(UINib(nibName: SEHospitalizeOrderInfoCell.className, bundle: nil), forCellReuseIdentifier: SEHospitalizeOrderInfoCell.reuseId)
            tableView.register(UINib(nibName: SEHospitalizeOrderImageCell.className, bundle: nil), forCellReuseIdentifier: SEHospitalizeOrderImageCell.reuseId)
            tableView.register(UINib(nibName: SEHospitalizeMemoCell.className, bundle: nil), forCellReuseIdentifier: SEHospitalizeMemoCell.reuseId)
            tableView.register(UINib(nibName: SERegistrationConfirmPatientCell.className, bundle: nil), forCellReuseIdentifier: SERegistrationConfirmPatientCell.reuseId)
            tableView.register(SECommentCell.nibForCell(), forCellReuseIdentifier: SECommentCell.reuseIdentifier())
        }
    }



    var viewModel = SEHospitalizeOrderDetailViewModel()

    init(with hospitalizeId: String) {
        self.viewModel.model.id = hospitalizeId
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        requestHospitalizeOrderDetail()
        // Do any additional setup after loading the view.
    }

    override func setupUI() {
        super.setupUI()

        viewModel.updateData = { status in
            switch status {
            case .success:
                self.tableView.isHidden = false
                self.tableView.reloadData()
            case .auth(let msg):
                self.presentLoginViewController(selector: #selector(self.requestHospitalizeOrderDetail)) {
                    SEHUD.showError(message: msg)
                }
            case .failure(let msg):
                SEHUD.showError(message: msg)
            }
        }

        viewModel.commentHandler = { status in
            switch status {
            case .success:
                SEHUD.show(message: "评价成功")
                self.requestHospitalizeOrderDetail()
            case .auth(let msg):
                self.presentLoginViewController(selector: #selector(self.submitCommentOfHospitalizeOrder)) {
                    SEHUD.showError(message: msg)
                }
            case .failure(let msg):
                SEHUD.showError(message: msg)
            }
        }

    }

    private func pushToChat() {
        var model = viewModel.model
        model.type = .online
        let vm = SEInquiryInfoViewModel(info: model)
        let vc = SEChatViewController(infoViewModel: vm)
        vc.title = model.doctorName
        navigationController?.pushViewController(vc, animated: true)
    }

    private func pushToPrescriptionOrderList() {
        let vc = SEPrescriptionOrderListViewController(prescriptionIds: [viewModel.model.id ?? ""])
        navigationController?.pushViewController(vc, animated: true)
    }

    private func showCommentView() {
        let comment = UINib.loadViewFrom(CommentView.self)
        comment.frame = CGRect(x: 0, y: 0, width: UIScreen.screenWidth, height: UIScreen.screenHeight)
        comment.delegate = self
        comment.show()
    }

}

// MARK: - UITableViewDataSource, UITableViewDelegate

extension SEHospitalizeOrderDetailViewController: UITableViewDataSource, UITableViewDelegate {

    // MARK: - UITableViewDataSource

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return viewModel.numberOfRowsInSection(section: section)
    }

    func numberOfSections(in tableView: UITableView) -> Int {
        return 8
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section == 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: SEHospitalizeOrderDoctorCell.reuseId, for: indexPath) as! SEHospitalizeOrderDoctorCell
            cell.updateCell(viewModel)
            return cell
        }
        if indexPath.section == 1 {
            let cell = tableView.dequeueReusableCell(withIdentifier: SEHospitalizeOrderPatientCell.reuseId, for: indexPath) as! SEHospitalizeOrderPatientCell
            cell.updateCell(viewModel)
            return cell
        }
        if indexPath.section == 2 {
            let cell = tableView.dequeueReusableCell(withIdentifier: SEHospitalizeOrderInfoCell.reuseId, for: indexPath) as! SEHospitalizeOrderInfoCell
            cell.updateCell(model: viewModel.infoModelArray[0])
            return cell
        }
        if indexPath.section == 3 {
            let cell = tableView.dequeueReusableCell(withIdentifier: SEHospitalizeOrderImageCell.reuseId, for: indexPath) as! SEHospitalizeOrderImageCell
            cell.updateCell(viewModel)
            return cell
        }
        if indexPath.section == 4 {
            let cell = tableView.dequeueReusableCell(withIdentifier: SEHospitalizeOrderInfoCell.reuseId, for: indexPath) as! SEHospitalizeOrderInfoCell
            cell.updateCell(model: viewModel.infoModelArray[1])
            return cell
        }
        if indexPath.section == 5 {
            let model = viewModel.memoModelArray[0]
            let cell = tableView.dequeueReusableCell(withIdentifier: SEHospitalizeMemoCell.reuseId, for: indexPath) as! SEHospitalizeMemoCell
            cell.updateCell(model: model)
            return cell
        }
        if indexPath.section == 6 {
            let model = viewModel.memoModelArray[1]
            let cell = tableView.dequeueReusableCell(withIdentifier: SEHospitalizeMemoCell.reuseId, for: indexPath) as! SEHospitalizeMemoCell
            cell.updateCell(model: model)
            return cell
        }
        if indexPath.section == 7 {
            if indexPath.row == 2 {
                let cell = tableView.dequeueReusableCell(withIdentifier: SECommentCell.reuseIdentifier(), for: indexPath) as! SECommentCell
                cell.updateData(score: Float(viewModel.model.rank), isComment: viewModel.model.rank > 0)
                return cell
            } else {
                let model = viewModel.entranceModelArray[indexPath.row]
                let cell = tableView.dequeueReusableCell(withIdentifier: SERegistrationConfirmPatientCell.reuseId, for: indexPath) as! SERegistrationConfirmPatientCell
                cell.updateCell(model: model)
                return cell
            }
        }
        return UITableViewCell()
    }

    // MARK: - UITableViewDelegate

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return viewModel.heightForRow(at: indexPath)
    }

    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let view = UIView()
        view.backgroundColor = UIColor.clear
        return view
    }

    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        switch section {
        case 0, 6: return 10
        default: return 0.01
        }
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        guard indexPath.section == 7 else { return }
        if indexPath.row == 0 {
            pushToChat()
        }
        if indexPath.row == 1 {
            guard viewModel.model.isPrescription != 0 else { return }
            pushToPrescriptionOrderList()
        }
        if indexPath.row == 2 {
            guard viewModel.model.rank == 0 else { return }
            showCommentView()
        }
    }
}

// MARK: - StarRatingViewDelegate

extension SEHospitalizeOrderDetailViewController: StarRatingViewDelegate {
    func starRatingView(_ starRatingView: StarRatingView, count: Float) {
        viewModel.model.rank = Int(count)
        tableView.reloadData()
        submitCommentOfHospitalizeOrder()
    }
}

// MARK: - APIRequest
extension SEHospitalizeOrderDetailViewController {
    @objc private func requestHospitalizeOrderDetail() {
        viewModel.requestHospitalizeOrderDetail()
    }

    @objc private func submitCommentOfHospitalizeOrder() {
        viewModel.submitCommentOfHospitalizeOrder()
    }
}
